import { fabric } from 'fabric'
import { Canvas } from 'fabric/fabric-impl'
import { ChildItem } from './ChildItem'
import { hasParentType } from './types/global'

export class ExpandButton {
	circle: fabric.Circle
	innerIcon: fabric.Line
	innerText: fabric.Text
	group: hasParentType<fabric.Group>
	canvas: Canvas
	parentItem: ChildItem
	constructor(canvas: Canvas, parentItem: ChildItem) {
		this.parentItem = parentItem
		this.canvas = canvas
		this.circle = new fabric.Circle({
			radius: 10,
			fill: '#fff',
			left: 0,
			top: 0,
			stroke: '#aaa',
			lockMovementX:true,
			lockMovementY:true,
			borderColor: 'transparent', // 控制器边框颜色
			cornerColor: 'transparent',  // 控制器几个控制柄的颜色
			strokeWidth: 1,
		})
		this.innerIcon = new fabric.Line([0, 0, 10, 0],{
			fill: 'black',
			stroke: '#aaa', 
			left: 5,
			top:10,
			objectCaching: false, 
			selectable: false,
		})
		this.innerText = new fabric.Text(this.parentItem.totalchildNum+'', {
			fontSize:16,
			fill: 'black',
			left: 0,
			top: 0,
			objectCaching: false, 
			selectable: false,
			originX: 'center',
			originY: 'center'
		})
		this.group = new fabric.Group([this.circle, this.innerIcon],{
			lockMovementX:true,
			lockMovementY:true,
			visible: false,borderColor: 'transparent', // 控制器边框颜色
			cornerColor: 'transparent',  // 控制器几个控制柄的颜色
		})
		this.group.parent = this.parentItem
		this.group.type = 'expandButtons'
		this.init()
	}
	init() {
		this.canvas.add(this.group)
		this.group.setControlsVisibility({
			'mtr':false,
			'bl':false,
			'br':false,
			'mb':false,
			'tl':false,
			'tr':false,
			'mt':false,
			'ml':false,
			'mr':false
		})
		this.group.on('mousedown',() => {
			this.parentItem.topLevel.sortFlag = false
			this.parentItem.topLevel.dragSort?.reset()
		})
		this.group.on('mouseup',() => {
			if(this.parentItem.childrenVisible){
				this.parentItem.hide()
				this.group.add(this.innerText)
				this.group.remove(this.innerIcon)
			}else{
				this.parentItem.show()
				this.group.remove(this.innerText)
				this.group.add(this.innerIcon)
			}
			this.parentItem.topLevel.countMapPosition()
			this.parentItem.topLevel._refresh()
		})
		this.group.on('selected', () => {
			this.parentItem.topLevel.select?.select([this.parentItem])
		})
	}
	show() {
		if(this.parentItem.children.length > 0) {
			this.group.visible = true
			this.group.remove(this.innerIcon)
			this.group.remove(this.innerText)
			if(this.parentItem.childrenVisible){
				this.group.add(this.innerIcon)
			}else{
				this.group.add(this.innerText)
			}
		}
	}
	hide() {
		if(this.parentItem.childrenVisible) {
			this.group.visible = false
		}
	}
	update() {
		this.innerText.setOptions({
			text: this.parentItem.totalchildNum + ''
		})
		this.group.setOptions({
			left: (this.parentItem.rect.left || 0) + this.parentItem.getWidth(),
			top: (this.parentItem.rect.top || 0) + this.parentItem.getHeight() / 2 - 10
		})
	}
	remove() {
		this.group && this.canvas.remove(this.group)
	}
}